package com.sjx.onelinecord.handler

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.MotionEvent
import androidx.appcompat.app.AppCompatActivity
import com.sjx.onelinecord.R
import com.sjx.onelinecord.http.HiOkHttp
import kotlinx.android.synthetic.main.activity_handler_aty.*


/**
 * 主线程不做耗时操作，子线程不更新UI
 */
@SuppressLint("HandlerLeak")
class HandlerAty : AppCompatActivity() {

    private var mHandler: Handler? = null
    private var hideHandler: Handler? = Handler()

    private var isShow: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_handler_aty)
        val handler: Handler = Handler()
        Thread(Runnable {
            handler.post { //耗时操作
                HiOkHttp.getAsync()
                Thread.sleep(1000)
                mTxHelloWorld.text = "HelloKotlin"
            }
        }).start()

        mHandler = object : Handler() {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                when (msg.what) {
                    0 -> mTxHelloWorld.text = msg.obj as CharSequence? //更新UI
                }
            }
        }


        initHandlerThread()

//        showOrHideThread()
    }

    private fun initHandlerThread() {
        Thread(Runnable {
            //执行耗时操作
            Thread.sleep(2000)
            val msg = Message()
            msg.what = 0
            msg.obj = "HelloZhiYanPeopleSjx"
            mHandler?.sendMessageDelayed(msg, 1 * 1000)
//            mHandler?.obtainMessage(0,"HelloZhiYanPeople")?.sendToTarget()
        }).start()
    }

    @SuppressLint("SetTextI18n")
    private fun isShowOrHide(isShow: Boolean) {
        if (!isShow) {
            Thread.sleep(3)
            mTxHelloWorld.text = "HelloAndroid"
        }
    }

    private fun showOrHideThread() {
        var runnable: Runnable = Runnable { isShowOrHide(false) }
        Thread(Runnable {
            hideHandler?.postDelayed(runnable, 4 * 1000)
        }).start()
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {

        when(event?.action) {
            MotionEvent.ACTION_DOWN -> {
                showOrHideThread()
            }
        }

        return super.onTouchEvent(event)
    }

}